Working with the File Type

The File type uses several static members to provide functionality almost identical to that of the FileInfo type. Like FileInfo, File supplies AppendText(), Create(), CreateText(), Open(), OpenRead(), OpenWrite(), and OpenText() methods. In many cases, you can use the File and FileInfo types interchangeably. To see this in action, you can simplify each of the previous FileStream examples by using the File type instead:

static void Main(string[] args)
{
    // Obtain FileStream object via File.Create().
    using(FileStream fs = File.Create(@"C:\Test.dat"))
    {}

    // Obtain FileStream object via File.Open().
    using(FileStream fs2 = File.Open(@"C:\Test2.dat",
        FileMode.OpenOrCreate,
        FileAccess.ReadWrite, FileShare.None))
    {}

    // Get a FileStream object with read-only permissions.
    using(FileStream readOnlyStream = File.OpenRead(@"Test3.dat"))
    {}

    // Get a FileStream object with write-only permissions.
    using(FileStream writeOnlyStream = File.OpenWrite(@"Test4.dat"))
    {}

    // Get a StreamReader object.
    using(StreamReader sreader = File.OpenText(@"C:\boot.ini"))
    {}

    // Get some StreamWriters.
    using(StreamWriter swriter = File.CreateText(@"C:\Test6.txt"))
    {}

    using(StreamWriter swriterAppend = File.AppendText(@"C:\FinalTest.txt"))
    {}
}

Additional File-centric Members

The File type also supports a few members shown in Table 20-6, which can greatly simplify the processes of reading and writing textual data.

Table 20-6. Methods of the File Type

Method Meaning in Life
ReadAllBytes() Opens the specified file, returns the binary data as an array of bytes, and then closes the file.
ReadAllLines() Opens a specified file, returns the character data as an array of strings, and then closes the file.
ReadAllText() Opens a specified file, returns the character data as a System.String, and then closes the file.
WriteAllBytes() Opens the specified file, writes out the byte array, and then closes the file.
WriteAllLines() Opens a specified file, writes out an array of strings, and then closes the file.
WriteAllText() Opens a specified file, writes the character data from a specified string, and then closes the file.

You can use these methods of the File type to read and write batches of data in only a few lines of code. Even better, each of these members automatically closes down the underlying file handle. For example, the following console program (named SimpleFileIO) persists the string data into a new file on the C: drive (and reads it into memory) with minimal fuss (this example assumes you have imported System.IO):

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("***** Simple IO with the File Type *****\n");
        string[] myTasks = {
            "Fix bathroom sink", "Call Dave",
            "Call Mom and Dad", "Play Xbox 360"};

        // Write out all data to file on C drive.
        File.WriteAllLines(@"C:\tasks.txt", myTasks);

        // Read it all back and print out.
        foreach (string task in File.ReadAllLines(@"C:\tasks.txt"))
        {
            Console.WriteLine("TODO: {0}", task);
        }
        Console.ReadLine();
    }
}

The lesson here: When you wish to obtain a file handle quickly, the File type will save you some keystrokes. However, one benefit of creating a FileInfo object first is that you can investigate the file using the members of the abstract FileSystemInfo base class.

Source Code You can find the SimpleFileIO project under the Chapter 20 subdirectory.